import Vue from 'vue';
import Vuex from 'vuex';

Vue.use(Vuex);

const types = {
    SET_SCOKET_CHANGE_COUNT: 'SET_SOCKET_CHANGE_COUNT',
    SET_CART_CHANGE_COUNT: 'SET_CART_CHANGE_COUNT',
    CART_LIST: 'CART_LIST',
    ORDER_ID: 'ORDER_ID'
};

const state = {
    socketChangeCount: 0,
    cartChangeCount: 0, // 进入预下单页时，还有其他人异步更新购物车，同步预下单也数据
    cartList: [],
    orderId: ''
};

const getters = {
    socketChangeCount: state => state.socketChangeCount,
    cartChangeCount: state => state.cartChangeCount,
    cartList: state => state.cartList,
    orderId: state => state.orderId
};

const mutations = {
    [types.SET_SCOKET_CHANGE_COUNT](state) {
        state.socketChangeCount++;
    },
    [types.SET_CART_CHANGE_COUNT](state) {
        state.cartChangeCount++;
    },
    [types.CART_LIST](state, cartList) {
        if (cartList) state.cartList = cartList;
        else state.cartList = [];
    },
    [types.ORDER_ID](state, orderId) {
        if (orderId) state.orderId = orderId;
        else state.orderId = '';
    }
};

const actions = {
    incrementSocket({commit}) {
        commit(types.SET_SCOKET_CHANGE_COUNT);
    },
    incrementCart({commit}) {
        commit(types.SET_CART_CHANGE_COUNT);
    },
    setCartList: ({commit}, cartList) => {
        commit(types.CART_LIST, cartList); // 这个list需要改为从本地Storage中取，而不是直接赋值
    },
    setOrderId: ({commit}, orderId) => {
        commit(types.ORDER_ID, orderId);
    }
};

export default new Vuex.Store({
    state,
    getters,
    mutations,
    actions
});
